<template>
  <div class="container">
    <Breadcrumb />
    <div class="rulesbox" v-if="!redshow">
      <!-- <a-tabs :default-active-key="tableid" @change="taskid">
        <a-tab-pane key="1" title="待审核列表">
          <a-card class="data-card">
            <a-row>
              <a-col :flex="1">
                <a-form
                  :model="formModel"
                  :label-col-props="{ span: 6 }"
                  :wrapper-col-props="{ span: 18 }"
                >
                  <a-row :gutter="26">
                    <a-col :span="5">
                      <a-form-item field="roomName" label="房间名称">
                        <a-input
                          v-model="formModel.roomName"
                          placeholder="请输入房间名"
                          allow-clear
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :span="5">
                      <a-form-item field="nickname" label="预约姓名">
                        <a-input
                          v-model="formModel.nickname"
                          placeholder="请输入姓名"
                          allow-clear
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :span="5">
                      <a-form-item field="nickname" label="用户类型">
                        <a-select
                          v-model="formModel.userType"
                          placeholder="请选择用户类型"
                          allow-clear
                        >
                          <a-option
                            v-for="item of userTypes"
                            :key="item.id"
                            :value="item.id"
                            >{{ item.name }}</a-option
                          >
                        </a-select>
                      </a-form-item>
                    </a-col>
                    <a-col :span="5">
                      <a-form-item field="appointmentNumber" label="预约人数">
                        <a-input
                          v-model="formModel.appointmentNumber"
                          placeholder="请输入人数"
                          allow-clear
                        />
                      </a-form-item>
                    </a-col>

                    <a-col :span="2">
                      <a-space :size="18">
                        <a-button type="primary" @click="onPageChange(1)">
                          <template #icon>
                            <icon-search />
                          </template>
                          搜索
                        </a-button>
                        <a-button @click="reset">
                          <template #icon>
                            <icon-refresh />
                          </template>
                          重置
                        </a-button>
                      
                      </a-space>
                    </a-col>
                  </a-row>
                </a-form>
              </a-col>
            </a-row>
            <a-divider style="margin-top: 0" />

            <a-table
              ref="userList"
              row-key="userId"
              v-model:selectedKeys="userIds"
              :loading="loading"
              page-position="bottom"
              :pagination="pagination"
              :columns="columns"
              :data="renderData"
              :bordered="false"
              @page-change="onPageChange"
              @page-size-change="onPageSizeChange"
            >
              <template #sex="{ record }">
                <template v-for="(item, index) in sexs">
                  <span v-if="record.sex == item.value">{{ item.label }}</span>
                </template>
              </template>

             
              <template #createUser="{ record }">
                {{ record.createUser }}({{
                  getAppointmentTypes(record.userType)
                }})
              </template>

              <template #startTime="{ record }">
                {{ formatDateTimeRange(record.startTime, record.endTime) }}
             
              </template>
              <template #option="{ record }">
                <a-space :size="18">
                  <a-button type="primary" @click="redmove(record)">
                    查看</a-button
                  >
                  <a-button
                    :disabled="record.auditStatus == 11"
                    type="primary"
                    status="success"
                    @click="passok(record)"
                    >通过</a-button
                  >

                  <a-button
                    status="danger"
                    @click="openEdit(record)"
                    :disabled="record.auditStatus == 11"
                  >
                    不通过</a-button
                  >
                </a-space>
              </template>
            </a-table>
          </a-card>
        </a-tab-pane>
        <a-tab-pane key="2" title="已审核列表">
          <a-card class="data-card">
            <a-row>
              <a-col :flex="1">
                <a-form
                  :model="formModel"
                  :label-col-props="{ span: 6 }"
                  :wrapper-col-props="{ span: 18 }"
                >
                  <a-row :gutter="26">
                    <a-col :span="5">
                      <a-form-item field="roomName" label="房间名称">
                        <a-input
                          v-model="formModel.roomName"
                          placeholder="请输入房间名"
                          allow-clear
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :span="5">
                      <a-form-item field="nickname" label="预约姓名">
                        <a-input
                          v-model="formModel.nickname"
                          placeholder="请输入姓名"
                          allow-clear
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :span="5">
                      <a-form-item field="nickname" label="用户类型">
                        <a-select
                          v-model="formModel.userType"
                          placeholder="请选择用户类型"
                          allow-clear
                        >
                          <a-option
                            v-for="item of userTypes"
                            :key="item.id"
                            :value="item.id"
                            >{{ item.name }}</a-option
                          >
                        </a-select>
                      </a-form-item>
                    </a-col>
                    <a-col :span="5">
                      <a-form-item field="appointmentNumber" label="预约人数">
                        <a-input
                          v-model="formModel.appointmentNumber"
                          placeholder="请输入人数"
                          allow-clear
                        />
                      </a-form-item>
                    </a-col>

                    <a-col :span="2">
                      <a-space :size="18">
                        <a-button type="primary" @click="onPageChange(1)">
                          <template #icon>
                            <icon-search />
                          </template>
                          搜索
                        </a-button>
                        <a-button @click="reset">
                          <template #icon>
                            <icon-refresh />
                          </template>
                          重置
                        </a-button>
                      </a-space>
                    </a-col>
                  </a-row>
                </a-form>
              </a-col>
            </a-row>
            <a-divider style="margin-top: 0" />

            <a-table
              ref="userList"
              row-key="userId"
              v-model:selectedKeys="userIds"
              :loading="loading"
              page-position="bottom"
              :pagination="pagination"
              :columns="columns"
              :data="renderData"
              :bordered="false"
              @page-change="onPageChange"
              @page-size-change="onPageSizeChange"
            >
              <template #sex="{ record }">
                <template v-for="(item, index) in sexs">
                  <span v-if="record.sex == item.value">{{ item.label }}</span>
                </template>
              </template>

           
              <template #createUser="{ record }">
                {{ record.createUser }}({{
                  getAppointmentTypes(record.userType)
                }})
              </template>

              <template #startTime="{ record }">
                {{ record.startTime }} -{{ record.endTime }}
              </template>
              <template #option="{ record }">
                <a-space :size="18">
                  <a-button type="primary" @click="redmove(record)">
                    查看详情</a-button
                  >
                
                </a-space>
              </template>
            </a-table>
          </a-card>
        </a-tab-pane>
      </a-tabs> -->
      <a-card class="data-card">
        <a-row>
          <a-col :flex="1">
            <a-form
              :model="formModel"
              :label-col-props="{ span: 6 }"
              :wrapper-col-props="{ span: 18 }"
            >
              <a-row :gutter="26">
                <a-col :span="5">
                  <a-form-item field="roomName" label="房间名称">
                    <a-input
                      v-model="formModel.roomName"
                      placeholder="请输入房间名"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="5">
                  <a-form-item field="nickname" label="预约姓名">
                    <a-input
                      v-model="formModel.nickname"
                      placeholder="请输入姓名"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="5">
                  <a-form-item field="nickname" label="用户类型">
                    <a-select
                      v-model="formModel.userType"
                      placeholder="请选择用户类型"
                      allow-clear
                    >
                      <a-option
                        v-for="item of userTypes"
                        :key="item.id"
                        :value="item.id"
                        >{{ item.name }}</a-option
                      >
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="5">
                  <a-form-item field="appointmentNumber" label="预约人数">
                    <a-input
                      v-model="formModel.appointmentNumber"
                      placeholder="请输入人数"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="5">
                  <a-form-item field="nickname" label="审核状态">
                    <a-select
                      v-model="formModel.auditStatus"
                      placeholder="请选择审核状态"
                      allow-clear
                    >
                      <a-option
                        v-for="item of auditStatusType"
                        :key="item.id"
                        :value="item.id"
                        >{{ item.name }}</a-option
                      >
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item field="nickname" label="日期范围">
                    <a-range-picker
                      v-model="formModeldate"
                      style="width: 360px; margin: 0 24px 24px 0"
                      format="YYYY-MM-DD"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="2">
                  <a-space :size="18">
                    <a-button type="primary" @click="onPageChange(1)">
                      <template #icon>
                        <icon-search />
                      </template>
                      搜索
                    </a-button>
                    <a-button @click="reset">
                      <template #icon>
                        <icon-refresh />
                      </template>
                      重置
                    </a-button>
                    <a-button @click="importdc">
                      <template #icon>
                        <icon-download />
                      </template>
                      批量导出</a-button
                    >
                  </a-space>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>
        <a-divider style="margin-top: 0" />

        <a-table
          ref="userList"
          row-key="appointmentId"
          v-model:selectedKeys="timetableId"
          :loading="loading"
          page-position="bottom"
          :pagination="pagination"
          :row-selection="rowSelection"
          :columns="columns"
          :data="renderData"
          :bordered="false"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
        >
          <template #sex="{ record }">
            <template v-for="(item, index) in sexs">
              <span v-if="record.sex == item.value">{{ item.label }}</span>
            </template>
          </template>

          <!-- <template #userType="{ record }">
                {{ getAppointmentTypes(record.userType) }}
              </template> -->
          <template #createUser="{ record }">
            {{ record.createUser }}({{ getAppointmentTypes(record.userType) }})
          </template>

          <template #startTime="{ record }">
            {{ formatDateTimeRange(record.startTime, record.endTime) }}
            <!-- {{ record.startTime }} -{{ record.endTime }} -->
          </template>
          <template #auditStatus="{ record }">
            {{ getAuditStatusText(record.auditStatus) }}

            <!-- {{ record.startTime }} -{{ record.endTime }} -->
          </template>

          <template #option="{ record }">
            <a-space :size="18">
              <a-button type="primary" @click="redmove(record)"> 查看</a-button>
              <a-button
                :disabled="
                  record.auditStatus == 11 ||
                  record.auditStatus == 1 ||
                  record.auditStatus == 2
                "
                type="primary"
                status="success"
                @click="openEdits(record)"
                >通过</a-button
              >

              <a-button
                status="danger"
                @click="openEdit(record)"
                :disabled="
                  record.auditStatus == 11 ||
                  record.auditStatus == 1 ||
                  record.auditStatus == 2
                "
              >
                不通过</a-button
              >
              <a-button status="danger" @click="delbookingfn(record)">
                删除</a-button
              >
            </a-space>
          </template>
        </a-table>
      </a-card>
    </div>
    <!-- 审核不通过原因 -->
    <a-modal
      @cancel="handleCancel"
      :on-before-ok="handleCheck"
      :mask-closable="false"
      unmountOnClose
      v-model:visible="addShow"
      width="600px"
    >
      <template #title> 审核 </template>
      <a-form ref="addModel" :rules="rules" :model="addForm">
        <a-row style="margin-bottom: 16px">
          <a-form-item label="审核不通过原因">
            <a-textarea
              placeholder="请输入审核不通过原因"
              allow-clear
              v-model="addForm.auditRemark"
            />
          </a-form-item>
        </a-row>
      </a-form>
    </a-modal>
    <!-- 审核通过 -->
    <a-modal
      @cancel="handleCancel"
      :on-before-ok="handleCheck"
      :mask-closable="false"
      unmountOnClose
      v-model:visible="addShows"
      width="600px"
    >
      <template #title> 审核 </template>
      <a-form ref="addModel" :rules="rules" :model="addForm">
        <a-row style="margin-bottom: 16px">
          <a-form-item label="审核通过备注">
            <a-textarea
              placeholder="审核通过备注"
              allow-clear
              v-model="addForm.auditRemark"
            />
          </a-form-item>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 已审核详情页面  需要判断是审核成功还是失败-->
    <a-card title="房间申请信息" v-if="redshow">
      <a-form :model="redForm">
        <a-row :gutter="10">
          <a-col :span="8">
            <a-form-item field="title" label="时间:">
              {{ redForm.startTime }}~{{ redForm.endTime }}</a-form-item
            >
            <a-form-item field="title" label="房间:">
              {{ redForm.roomName }}</a-form-item
            >
          </a-col>
          <a-col :span="8">
            <a-form-item field="title" label="预约人:">
              {{ redForm.createUser }}</a-form-item
            >
            <a-form-item field="title" label="使用人数:">
              {{ redForm.appointmentNumber }}</a-form-item
            >
          </a-col>
          <a-col :span="8">
            <a-form-item field="title" label="预约人信用分:">
              {{ redForm.userCredit }}</a-form-item
            >
            <a-form-item field="title" label="主题:">
              {{ redForm.appointmentTheme }}</a-form-item
            >
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card title="审批记录" v-if="redshow">
      <a-form :model="redForm">
        <a-row :gutter="10">
          <a-col :span="8">
            <a-form-item field="title" label="审批时间:">
              {{ redForm.auditTime }}</a-form-item
            >
            <a-form-item field="title" label="审批结果:">
              {{
                redForm.auditStatus == '1'
                  ? '审核通过'
                  : redForm.auditStatus == '2'
                  ? '审核不通过'
                  : redForm.auditStatus == '9'
                  ? '待审核'
                  : '状态未知'
              }}</a-form-item
            >
            <a-form-item field="title" label="审批备注:">
              {{
                redForm.auditRemark == null || redForm.auditRemark.trim() === ''
                  ? '暂未备注'
                  : redForm.auditRemark
              }}</a-form-item
            >
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <!-- evaluateStatus 评价状态 1 已评价 9未评价 null 未知状态 -->
    <!-- 判断状态 如果已评价 去获取信用分变动情况 没评价不需要获取 需要获取全局的参数进行扣分 -->
    <a-card title="验收评价" v-if="redshow && redForm.auditStatus == '1'">
      <!-- 未评价 -->
      <a-form
        class="yspkbbox"
        :model="redForm"
        v-if="redForm.evaluateStatus == '9' || redForm.evaluateStatus == null"
      >
        <a-row :gutter="10">
          <a-col :span="24" class="yspk">
            <a-checkbox-group
              direction="vertical"
              v-model="sletoptions"
              @change="sletoptionsfn"
            >
              <a-checkbox
                :value="item.cause"
                v-for="item in options"
                :key="item.index"
                >{{ item.cause }} ~ {{ item.score }}分</a-checkbox
              >
            </a-checkbox-group>
          </a-col>
        </a-row>
      </a-form>
      <!-- 已评价 -->
      <div class="divTabled" v-if="redForm.evaluateStatus == '1'">
        <!-- <div class="rows">
            <div class="cell">增减变化</div>
            <div class="cell">增减变化</div>
            <div class="cell">行为详情 </div>
            <div class="cell">发生时间 </div>
          </div> -->
        <div
          class="rowd"
          v-for="item in redForm.evaluateContent"
          v-if="redForm.evaluateContent.length > 0"
        >
          {{ item.cause }} -{{ item.score }}分
        </div>
        <div v-else class="rowdd"> 暂无数据 </div>
      </div>
      <!-- <a-timeline v-if="redForm.evaluateStatus == '1'">
        <div class="divTable">
          <div class="rows">
            <div class="cell">增减变化</div>
            <div class="cell">增减变化</div>
            <div class="cell">行为详情 </div>
            <div class="cell">发生时间 </div>
          </div>
          <div
            class="row"
            v-for="item in creditlist"
            v-if="creditlist.length > 0"
          >
            <div class="cells">
              <a-timeline-item> -{{ item.score }}分</a-timeline-item></div
            >
            <div class="cell">信用分余额{{ item.balance }}分</div>
            <div class="cell">{{ item.cause }}</div>
            <div class="cell">{{ item.createTime }}</div>
          </div>
          <div v-else class="rowdd"> 暂无数据 </div>
        </div></a-timeline
      > -->
    </a-card>
    <a-card
      title="详情图片"
      v-if="
        redshow && redForm.auditStatus == '1' && redForm.evaluateStatus == '9'
      "
    >
      <a-form-item field="roomPhoto" label="图片:" class="xqphpo">
        <div class="wrap">
          <!-- 上传后显示 -->
          <div id="look">
            <div id="look_img" v-for="(item, index) in roomPhoto" :key="index">
              <div class="item_img">
                <img :src="base + item" />
                <div class="look_event">
                  <img
                    src="@/assets/images/vMEaxH.png"
                    title="点击删除"
                    @click="deletes(item, index)"
                  />
                </div>
              </div>
              <span class="item_time">{{ item.uptime }}</span>
            </div>
            <!-- 上传图片按钮 -->
            <a-upload
              class="updiv"
              v-if="roomPhoto.length < 5"
              v-model="roomPhoto"
              @change="onChange"
              image-preview
              :limit="6"
              :multiple="true"
              :auto-upload="false"
              :show-file-list="false"
              accept=".png,.jpg"
            >
              <template #upload-button>
                <div
                  style="
                    background-color: var(--color-fill-2);
                    color: var(--color-text-1);
                    border: 2px dashed var(--color-fill-4);
                    height: 80px;
                    width: 80px;
                    line-height: 80px;
                    text-align: center;
                  "
                >
                  <div> 上传图片 </div>
                </div>
              </template>
            </a-upload>
          </div>
        </div>
      </a-form-item>
      <div>最多上传5张</div>
    </a-card>
    <a-card
      title="详情图片"
      v-if="
        redshow && redForm.auditStatus == '1' && redForm.evaluateStatus == '1'
      "
    >
      <a-form-item field="roomPhoto" label="图片:" class="xqphpo">
        <div class="wrap">
          <!-- 上传后显示 -->
          <div id="look">
            <div
              id="look_img"
              v-for="(item, index) in parseJSONs(redForm.evaluatePhoto)"
              :key="index"
            >
              <div class="item_img">
                <img :src="base + item" />
                <span
                  v-if="
                    item == null || item == '' || item == undefined || !item
                  "
                  >暂无上传</span
                >
              </div>
            </div>
          </div>
        </div>
      </a-form-item>
    </a-card>
    <a-card v-if="redshow">
      <div class="redan">
        <a-button type="primary" @click="redshow = false">返回</a-button>
        <a-button
          type="primary"
          status="success"
          @click="savefn(redForm)"
          v-if="
            (redForm.evaluateStatus == '9' || redForm.evaluateStatus == null) &&
            redForm.auditStatus == '1' &&
            tjshow
          "
          >提交</a-button
        >

        <a-button
          type="primary"
          status="success"
          @click="openEdits(redForm)"
          v-if="redForm.auditStatus == '9' && redForm.auditStatus != '11'"
          >通过</a-button
        >

        <a-button
          status="danger"
          @click="openEdit(redForm)"
          v-if="redForm.auditStatus == '9' && redForm.auditStatus != '11'"
        >
          不通过</a-button
        >
      </div>
    </a-card>
    <!-- 删除提示弹窗 -->
    <a-modal
      v-model:visible="visiblets"
      @ok="handleOkts"
      @cancel="handleCancelts"
    >
      <template #title> 提示 </template>
      <div style="color: red; text-align: left"
        >该条预约记录当前为生效状态，是否删除？删除后无法恢复，请谨慎操作！</div
      >
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { Message, Modal } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { computed, ref, reactive, inject, getCurrentInstance } from 'vue';
  import {
    roomList,
    roomAudit,
    creditList,
    saveEvaluate,
    creditfs,
    bookingInfo,
    importDc,
    delbooking,
    uploadFile,
  } from '@/api/roombooking';
  import { putProgress } from '@/utils/oss.js';
  // 删除相关操作
  const handleCancelts = () => {
    zcdata.value = '';
    visiblets.value = false;
  };
  const zcdata = ref();
  const handleOkts = () => {
    delbooking({
      appointmentId: zcdata.value.appointmentId,
    }).then((res) => {
      if (res.code == 200) {
        Message.success({
          content: '删除成功!',
        });

        fetchData();
        zcdata.value = '';
      }
    });
  };
  const visiblets = ref(false);
  // 删除
  const delbookingfn = (item) => {
    if (item.auditStatus == 11 || item.auditStatus == 2) {
      delbooking({
        appointmentId: item.appointmentId,
      }).then((res) => {
        if (res.code == 200) {
          Message.success({
            content: '删除成功!',
          });
          // pagination.current = 1;
          fetchData();
        }
      });
    } else {
      zcdata.value = item;
      visiblets.value = true;
    }
  };
  // 导出相关操作代码
  const formModeldate = ref([]);
  const timetableId = ref([]);
  const importdc = () => {
    console.log('formModel.auditStatus', formModel.value.auditStatus);

    if (
      formModel.value.auditStatus == '' ||
      formModel.value.auditStatus == undefined
    ) {
      Modal.confirm({
        title: '提示',
        content: '请先选择审核状态',
        onOk() {},
      });
    } else {
      importDc({
        auditStatus: formModel.value.auditStatus,
        startDate: formModeldate.value[0],
        endDate: formModeldate.value[1],
        deviceName: formModel.value.deviceName,
        userType: formModel.value.userType,
        appointmentIdList: timetableId.value,
      }).then((res) => {
        console.log('导出成功', res.data);
      });
    }
  };
  // 导出相关操作代码结束
  // 图片上传相关逻辑操作
  // 全局变量，用于存储上传的图片信息
  let roomPhoto = ref<string[]>([]);
  // 图片上传oss
  const base = ref(window.config.VUE_APP_BASE_IMG);
  const { proxy } = getCurrentInstance();
  const onChange = (fileList: { file: File }[] | string) => {
    console.log('检测到上传图片', fileList);

    if (Array.isArray(fileList) && fileList.length > 0) {
      // console.log('清空之前的数据', fileList);
      roomPhoto.value = [];

      const mainkey = window.config.VUE_APP_BASE_KEY;
      const uploadTasks = fileList.map((item) => {
        const key = `${mainkey}/room/images/${item.file.name}`;
        // return putProgress(key, item.file).then(
        //   (res: { data: { code: number; data: any } }) => {
        //     if (res && res.data && res.data.code === 200) {
        //       return proxy.baseurl + res.data.data;
        //     } else {
        //       return proxy.baseurl + key;
        //     }
        //   }
        // );
        let formData = new FormData();
        formData.append('file', item.file);
        return uploadFile(formData).then((res) => {
          if (res.code == 200) {
            console.log('上传成功', res);
            return res.data;
          }
        });
      });

      Promise.all(uploadTasks).then((urls) => {
        console.log('原本的图片', redForm.roomPhoto);

        roomPhoto.value = [...urls]; // 将上传成功的 URL 添加到 roomPhoto.value 中
        redForm.roomPhoto = JSON.stringify(roomPhoto.value); // 更新表单中的 roomPhoto 字段

        console.log('成功返回的图片地址', roomPhoto.value);
        // 清空 fileList
        // fileList.splice(0, fileList.length);
        // console.log('上传完成后清空 fileList:', fileList);
      });
    }
  };
  // 删除图片
  const deletes = (item, index) => {
    if (Array.isArray(roomPhoto)) {
      console.log('myArray 是一个数组');
    } else {
      console.log('myArray 不是一个数组');
    }
    console.log('当前图片类型', roomPhoto.value);

    roomPhoto.value.splice(index, 1);
    // imageUrl.value = imageUrl.value?.filter((el) => el !== item.imgname);
  };
  function parseJSONs(str) {
    try {
      return JSON.parse(str);
    } catch (error) {
      // JSON.parse 出错时捕获异常
      // console.error('解析 JSON 出错:', error);
      return str;
    }
  }
  // function parseJSON(str) {
  //   try {
  //     return JSON.parse(str)[0];
  //   } catch (error) {
  //     // JSON.parse 出错时捕获异常
  //     // console.error('解析 JSON 出错:', error);
  //     return str[0];
  //   }
  // }
  // 图片上传相关逻辑完成
  const tjshow = ref('true');
  const { loading, setLoading } = useLoading(true);
  const creditlist = ref([]);
  const redshow = ref(false);
  let redForm = reactive({});
  const savefn = (item) => {
    console.log(item);

    saveEvaluate({
      appointmentId: item.appointmentId,
      userId: item.createUserId,
      appointmentEvaluateList: EvaluateList.value,
      associatedType: 'ROOM',
      evaluatePhoto: redForm.roomPhoto,
    }).then((res) => {
      if (res.code == '200') {
        Message.success({
          //   content: res.message,
          content: '评价成功',
        });
        tjshow.value = false;
        redForm.evaluateStatus = 1;
        // onBeforeRouteUpdate(() => {
        //   // 执行需要的刷新逻辑
        // });
        // redshow.value = false;
        // reset();
        // redmove(redForm);
      } else {
      }
    });
  };
  function getAuditStatusText(status: number): string {
    switch (status) {
      case 1:
        return '已通过';
      case 2:
        return '不通过';
      case 9:
        return '待审核';
      case 11:
        return '已过期';
      default:
        return '未知状态';
    }
  }
  const credit = () => {
    try {
      creditList({ type: 'ROOM' }).then((res) => {
        console.log('获取信用分扣分选项', res);
        if (res.code == 200) {
          options.value = res.data;
          // EvaluateList.value = res.data;
        }
      });
    } catch (error) {}
  };
  const options = ref([]);
  const sletoptions = ref([]);
  const sletoptionsfn = () => {
    EvaluateList.value = [];
    sletoptions.value.forEach((selectItem) => {
      // let selectedCause = Object.values(selectItem)[0]; // 获取选择数组中的原因值
      // console.log('原数组值', selectedCause, selectItem);

      // 在options数组中查找匹配的条目
      let matchingOption = options.value.find(
        (option) => option.cause === selectItem
      );
      // console.log('修改后数据', matchingOption);

      if (matchingOption) {
        EvaluateList.value.push(matchingOption);
      }
    });

    console.log('选择的信用分变动', EvaluateList.value);
  };
  // 创建一个存储选择分值列表的数据
  const EvaluateList = ref([]);
  // 查看详情
  const redmove = (item) => {
    console.log('查看详情', item.appointmentId);
    bookingInfo({ appointmentId: item.appointmentId }).then((res) => {
      console.log('返回数据', res.data);
      if (res.code == 200) {
        redForm = { ...res.data };
        redshow.value = true;
      }
    });
    // redForm = { ...item };
    // redshow.value = true;

    if (
      (item.evaluateStatus == '9' || item.evaluateStatus == null) &&
      item.auditStatus == '1'
    ) {
      credit();
    }
    if (item.evaluateStatus == '1') {
      creditfs({
        userId: item.createUserId,
      }).then((res) => {
        console.log('当前扣分详细记录', res);

        creditlist.value = res.data;
      });
    }
  };
  const generateDataModel = () => {
    return {
      roomId: '',
      startTime: '',
      endTime: '',
      appointmentId: '',
      auditStatus: '',
      auditRemark: '',
    };
  };

  const addModel = ref();
  const addForm = ref(generateDataModel());
  // 提交审核失败
  const handleCheck = (done) => {
    // if (loading.value) {
    //   done(false);
    //   return;
    // }
    // setLoading(true);
    // setTimeout(() => {
    //   setLoading(false);
    // }, 1500);
    addModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        // if (!errors) {

        // } else {
        //   done(false);
        // }
        roomAudit({ ...addForm.value }).then((res) => {
          if (res.code == '200') {
            Message.success({
              //   content: res.message,
              content: '审核成功！',
            });
            redshow.value = false;
            done(true);
            reset();
          } else {
            done(false);
          }
        });
      }
    );
  };
  const addShows = ref(false);
  const openEdits = (item) => {
    console.log('item', item);

    addForm.value.roomId = item.roomId;
    addForm.value.startTime = item.startTime;
    addForm.value.endTime = item.endTime;
    addForm.value.appointmentId = item.appointmentId;
    addForm.value.auditStatus = '1';
    addForm.value.createUserId = item.createUserId;
    addShows.value = true;

    // console.log('ss', rules.username[0].required);
  };
  const openEdit = (item) => {
    addForm.value.roomId = item.roomId;
    addForm.value.startTime = item.startTime;
    addForm.value.endTime = item.endTime;
    addForm.value.appointmentId = item.appointmentId;
    addForm.value.auditStatus = '2';
    addForm.value.createUserId = item.createUserId;
    addShow.value = true;

    // console.log('ss', rules.username[0].required);
  };
  const addShow = ref(false);
  const handleCancel = () => {
    addShow.value = false;
    addShows.value = false;
    addForm.value = [];
  };
  // 通过
  const passok = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确认通过吗？',
      onOk() {
        try {
          const data = {
            roomId: item.roomId,
            startTime: item.startTime,
            endTime: item.endTime,
            appointmentId: item.appointmentId,
            auditStatus: '1',
            auditRemark: '',
            createUserId: item.createUserId,
          };
          roomAudit(data).then((res) => {
            if (res.code == '200') {
              Message.success({
                //   content: res.message,
                content: '审核完成',
              });
              redshow.value = false;
              fetchData();
            }
          });
        } catch (err) {
          console.log(err);
        } finally {
          setLoading(false);
        }
      },
    });
  };
  const userTypes = reactive([
    { id: 'TEACHER', name: '老师' },
    { id: 'STUDENT', name: '学生' },
    { id: 'VISITOR', name: '访客' },
  ]);

  // const getAppointmentTypes = (openAppointment: string) => {
  //   const types = openAppointment.split(','); // 将字符串按逗号分割成数组
  //   return types.map((type: string) => getAppointmentType(type)).join(', '); // 调用 getAppointmentType 转换为中文后再连接成字符串
  // };
  const getAppointmentTypes = (openAppointment: string) => {
    // 检查 openAppointment 是否为字符串
    if (typeof openAppointment !== 'string') {
      return openAppointment; // 或者返回 null，视你的需求而定
    }

    const types = openAppointment.split(','); // 将字符串按逗号分割成数组
    return types.map((type: string) => getAppointmentType(type)).join(', '); // 调用 getAppointmentType 转换为中文后再连接成字符串
  };
  const getAppointmentType = (type: string): string => {
    switch (type) {
      case 'TEACHER':
        return '老师';
      case 'STUDENT':
        return '学生';
      case 'VISITOR':
        return '访客';
      default:
        return '';
    }
  };
  // const generateLockModel = () => {
  //   return {
  //     userIds: '',
  //   };
  // };

  const userIds = ref([]);

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const renderData = ref([]);
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });
  const tableid = ref('1');
  //   全局切换table
  const taskid = (i) => {
    tableid.value = i;
    // console.log('切换', i);
    fetchData();
  };
  // 实例化搜索表单
  const generateFormModel = () => {
    return {
      roomName: '',
      nickname: '',
      appointmentNumber: '',
      userType: '',
      auditStatus: '',
    };
  };
  // 搜索表单
  const formModel = ref(generateFormModel());

  // 表格表头
  const columns = computed<TableColumnData[]>(() => [
    {
      title: '序号',
      dataIndex: 'appointmentId',
    },
    {
      title: '预约时段',
      dataIndex: 'startTime',
      slotName: 'startTime',
      align: 'center',
    },

    {
      title: '预约房间',
      dataIndex: 'roomName',
      //   slots: 'content',
    },

    {
      title: '预约人(类型)',
      dataIndex: 'createUser',
      slotName: 'createUser',
    },
    {
      title: '使用人数',
      dataIndex: 'appointmentNumber',
    },
    {
      title: '主题',
      dataIndex: 'appointmentTheme',
    },
    {
      title: '审批状态',
      dataIndex: 'auditStatus',
      slotName: 'auditStatus',
    },
    {
      title: '操作',
      dataIndex: 'option',
      slotName: 'option',
      align: 'center',
    },
  ]);
  // 请求表格数据
  const fetchData = async () => {
    setLoading(true);
    try {
      // if (tableid.value == '1') {
      //   formModel.value.auditStatus = '9';
      // } else {
      //   formModel.value.auditStatus = '1';
      // }
      const data = {
        startDate: formModeldate.value[0],
        endDate: formModeldate.value[1],
        pageNum: pagination.current,
        ...pagination,
        ...formModel.value,
      };
      roomList(data).then((res) => {
        let list = res.data.list || [];

        renderData.value = list;
        pagination.total = res.data.total;
        pagination.current = res.data.pageNum;

        // userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };
  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };
  const auditStatusType = reactive([
    { id: '1', name: '已通过' },
    { id: '2', name: '未通过' },
    { id: '9', name: '待审核' },
    { id: '11', name: '已过期' },
  ]);
  const reset = () => {
    formModel.value = generateFormModel();
    addForm.value = generateDataModel();
    formModeldate.value = [];
    fetchData();
  };
  fetchData();
  function formatDateTimeRange(startDateTimeStr, endDateTimeStr) {
    // 提取日期部分
    const startDate = new Date(startDateTimeStr);
    const endDate = new Date(endDateTimeStr);

    // 提取时间部分
    const startTime = startDate.toLocaleTimeString([], {
      hour: '2-digit',
      minute: '2-digit',
    });
    const endTime = endDate.toLocaleTimeString([], {
      hour: '2-digit',
      minute: '2-digit',
    });

    // 格式化成期望的格式
    const formattedDateTimeRange = `${
      startDate.toISOString().split('T')[0]
    } ${startTime}~${endTime}`;

    return formattedDateTimeRange;
  }
</script>

<style lang="less">
  .rulesbox {
    background-color: #fff;
  }
  .rulesbox .arco-tabs-tab {
    font-size: 17px !important;
  }
  .redan {
    text-align: center;
  }
  .redan button {
    margin: 0 10px;
  }
  .divTable {
    display: flex;
    flex-direction: column;
    max-height: 400px;
    /* background-color: red; */
    overflow-y: auto;
  }
  .row {
    display: flex;
  }
  .rows {
    display: flex;
    font-size: 18px;
    text-align: center;
  }
  .cell {
    text-align: center;
    width: 400px;
    height: 30px;
  }
  .cells {
    width: 400px;
    padding-left: 170px;
  }
  .divTable .arco-timeline-item {
    min-height: 30px;
  }
  .backf {
    text-align: center;
  }
  .rowdd {
    font-size: 16px;
    text-align: center;
    margin: 20px 0;
  }
  .yspkbbox {
    height: 170px;
    overflow-x: hidden;
    overflow-y: auto;
  }
  .yspk {
    display: flex;
    flex-wrap: wrap;
    height: 170px;
  }
  .yspk .arco-checkbox {
    width: 600px;
    display: inline-block !important;
  }

  .wrap {
    width: 100%;
  }
  #demo {
    width: 200px;
    height: 200px;
    box-sizing: border-box;
    position: relative;
    border: 2px dashed #dcdcdc;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 8px 5px 20px 5px;
  }

  #demo_file {
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    cursor: pointer;
  }

  #demo_img {
    display: block;
    width: 50%;
    height: 50%;
  }

  #look {
    display: flex;
    flex-wrap: wrap;
    justify-content: left;
    align-items: center;
  }

  #look_img {
    width: 80px;
    height: 80px;
    margin: 8px 5px 20px 5px;
  }
  .item_img {
    border: 2px dashed #dcdcdc;
    width: 80px;
    height: 80px;
    box-sizing: border-box;
    position: relative;
    img {
      display: block;
      cursor: pointer;
      width: 100%;
      height: 100%;
      padding: 5px;
      box-sizing: border-box;
    }
  }
  .item_time {
    height: 10px;
  }

  .look_event {
    width: 100%;
    height: 0;
    background: rgba(0, 0, 0, 0.6);
    position: absolute;
    top: 0;
    left: 0;
    transition: 1s;
    display: flex;
    justify-content: center;
    align-items: center;

    img {
      display: block;
      width: 200px;
      height: 0;
      cursor: pointer;
    }
  }

  .item_img:hover .look_event {
    height: 100%;
    opacity: 70%;
  }

  .item_img:hover .look_event > img {
    height: 4em;
  }

  .preview_img {
    width: 450px;
    height: 450px;
  }
  .divTabled {
    display: flex;
    height: auto; /* 自动调整高度 */
    max-height: 160px; /* 最大高度 */
    width: 100%;
    flex-wrap: wrap;
    overflow: auto; /* 如果内容超出，可以滚动 */
  }
  .rowd {
    display: flex;
    flex-wrap: wrap; /* 允许内容自动换行 */
    height: auto; /* 自动调整高度 */
    width: 600px; /* 或者根据需要设置具体宽度 */
    margin: 5px 1px;
  }
</style>
